using System;
using System.IO;
using DataLayer.Repositories;
using DbEntities.Entities;
using EsbMonitor.Ninject;
using EsbMonitorMessages;
using NServiceBus;

namespace EsbMonitor.Handlers
{
    public class MessageAssemblyLoadedEventHandler : IHandleMessages<IMessageAssemblyLoadedEvent>
    {
        public IBus Bus { get; set; }

        #region IHandleMessages<IMessageAssemblyLoadedEvent> Members

        public void Handle(IMessageAssemblyLoadedEvent message)
        {
            var messageAssembliesRepository = KernelContainer.Get<IMessageAssembliesRepository>();

            string messageAssemblyVersionId = message.ModuleVersionId.ToString();

            if (messageAssembliesRepository.FindByMessageAssemblyVersionId(messageAssemblyVersionId) == null)
            {
                string path = @"d:\temp\esb\" + message.ModuleVersionId + ".dll";

                File.WriteAllBytes(path, message.BinaryData);

                Console.WriteLine("saved file " + path);

                var messageAssembly = new MessageAssembly
                                          {
                                              FileName = message.FileName,
                                              FileSize = message.BinaryData.Length,
                                              LocalName = path,
                                              MessageAssemblyVersionId = messageAssemblyVersionId
                                          };

                messageAssembliesRepository.Add(messageAssembly);
            }
        }

        #endregion
    }
}